﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using HybridCLR.Editor.Commands;
using HybridCLR.Editor;
using System.Linq;
using System.IO;
using System.Xml.Linq;

public class BuildCommandTool
{
    static BuildConfigSO BuildConfigSO;

    static BuildCommandTool()
    {
        BuildConfigSO = AssetDatabase.FindAssets($"t:{nameof(BuildConfigSO)}").Select(a => AssetDatabase.LoadAssetAtPath<BuildConfigSO>(AssetDatabase.GUIDToAssetPath(a))).First();
    }

    [MenuItem("BuildTools/OpenPersistenDataPath")]
    static void OpenPersistentDataPath()
    {
        Application.OpenURL(Application.persistentDataPath);
    }

    /// <summary>
    /// 打包热更脚本
    /// </summary>
    [MenuItem("BuildTools/编译热更DLL和补充元数据的DLL到打包目录")]
    static void PackHotFixDll()
    {
        //执行HybirdCLR编译脚本命令
        BuildTarget target = EditorUserBuildSettings.activeBuildTarget;
        CompileDllCommand.CompileDll(target);
        //编译后AOT程序集输出的目录
        string aotAssembliesSrcDir = SettingsUtil.GetAssembliesPostIl2CppStripDir(target);
        //AOT程序集和热更程序集目标目录
        string hotFixAssembliesDstDir = Path.Combine(Application.dataPath, BuildConfigSO.HotFixScriptDllRelativeFolder);
        Debug.Log(hotFixAssembliesDstDir);
        if (!Directory.Exists(hotFixAssembliesDstDir))
        {
            Directory.CreateDirectory(hotFixAssembliesDstDir);
        }
        else
        {
            var files = Directory.EnumerateFiles(hotFixAssembliesDstDir);
            foreach (var file in files)
            {
                Debug.Log(file);
                FileUtil.DeleteFileOrDirectory(file);
            }
        }
        //AssetDatabase.Refresh();
        //return;
        foreach (var dll in SettingsUtil.AOTAssemblyNames)
        {
            string srcDllPath = $"{aotAssembliesSrcDir}/{dll}.dll";
            if (!File.Exists(srcDllPath))
            {
                Debug.LogError($"ab中添加AOT补充元数据dll:{srcDllPath} 时发生错误,文件不存在。裁剪后的AOT dll在BuildPlayer时才能生成，因此需要你先构建一次游戏App后再打包。");
                continue;
            }
            string dllBytesPath = $"{hotFixAssembliesDstDir}/{dll}.dll.bytes";
            File.Copy(srcDllPath, dllBytesPath, true);
            Debug.Log($"[CopyAOTAssembliesToStreamingAssets] copy AOT dll {srcDllPath} -> {dllBytesPath}");
        }
        //复制HotFix程序集到指定打包目录
        string hotfixDllSrcDir = SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target);
        foreach (var dll in SettingsUtil.HotUpdateAssemblyFilesExcludePreserved)
        {
            string dllPath = $"{hotfixDllSrcDir}/{dll}";
            string dllBytesPath = $"{hotFixAssembliesDstDir}/{dll}.bytes";
            File.Copy(dllPath, dllBytesPath, true);
            Debug.Log($"[CopyHotUpdateAssembliesToStreamingAssets] copy hotfix dll {dllPath} -> {dllBytesPath}");
        }
        Debug.Log("打包Aot和热更程序集开始========================Finish!!!!");
        AssetDatabase.Refresh();
    }
}
